<template>
  <div v-if="!printShow">
    <div class="front">
      <el-collapse v-model="activeNames" class="front-collapse"
        @change="activeNames = !activeNames; collapseName == '收起' ? collapseName = '展开' : collapseName = '收起'">
        <el-collapse-item :title="collapseName" class="collapse-1" name="1">
          <el-form :model="searchForm" label-width="120px" inline="true">
            <el-form-item label="入库单号" class="front-input">
              <el-input v-model="searchForm.orderCode" />
            </el-form-item>
            <el-form-item label="所属仓库" class="front-input">
              <el-select v-model="searchForm.desWarehouseId" placeholder="请选择仓库">
                <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" class="front-input">
              <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" prop="supplierId">
                <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="tail">
      <div class="tail-action" style="margin-bottom: 10px;">
        <el-button type="primary">导出明细</el-button>
        <el-button type="primary" @click="printSelectedRows">直接打印入库单</el-button>
        <el-button type="primary" @click="designPrint">自定义打印入库单</el-button>
        <!-- <el-button type="primary">打印明细</el-button> -->
        <el-button type="primary" @click="mergeOrder">合并入库单</el-button>

        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" v-loading="tableLoading"
        @selection-change="handleChangeSelection" >
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column type="selection"/>
        <el-table-column v-for="item in inboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
          :max-width="item.maxWidth" :label="item.label">
          <template v-if="true" v-slot:default="scope">
            <!--1. 状态 -->
            <div size="small" v-if="item.prop == 'status'">
              <el-tag v-if="scope.row[item.prop] === 0" type="success">启动</el-tag>
              <el-tag v-else-if="scope.row[item.prop] === 1" type="info">停用</el-tag>
            </div>
            <!--2. 删除标志 -->
            <div size="small" v-else-if="item.prop == 'delFlag'">
              <el-tag v-if="scope.row[item.prop] === '0'" type="success">存在</el-tag>
              <el-tag v-else-if="scope.row[item.prop] === '2'" type="info">删除</el-tag>
            </div>
            <!--3. 合并标志 -->
            <div size="small" v-else-if="item.prop == 'merged'">
              <el-tag v-if="scope.row[item.prop] === 0">未被合并</el-tag>
              <el-tag v-if="scope.row[item.prop] === 1" type="success">被合并</el-tag>
              <el-tag v-else-if="scope.row[item.prop] === 2" type="info">合并后</el-tag>
            </div>
            <!-- 4. 默认展示 -->
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
    <template #default="scope">
        <!-- <el-button link type="primary" size="small" @click="printTag(scope.row)">打印标签</el-button> -->
        <el-button link type="primary" size="small" @click="openDetails(scope.row)">查看明细</el-button>
        <el-button link type="primary" size="small">编辑备注</el-button>
        <el-button v-if="scope.row.orderType === '采购入库'" link type="primary" size="small" @click="() => handleDeleteInboundOrder(scope.row.id)">删除</el-button>

    </template>
</el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" v-model:total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>

    <div class="dialog-list">
      <div>
        <el-dialog v-model="dialogVisiblePrint">
          <div id="printArea" class="right-print">
            <vue-barcode :value="rowDetails.orderCode" format="CODE128" displayValue="true" width="1" height="35"
              font-size="15"></vue-barcode>
            <el-button v-print="printTest">打印</el-button>
          </div>
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="drawer" width="80%" title="入库单明细">
          <el-table :data="rowDetails" border size="80%" max-height="500">
            <el-table-column prop="jadeName" label="货品名称" min-width="60" />
            <el-table-column prop="jadeTypeName" label="货品品类" min-width="60" />
            <el-table-column prop="jadeBarcode" label="货品编码" min-width="60" />
            <el-table-column prop="jadeCost" label="成本价" min-width="60" />
            <el-table-column prop="jadeTagPrice" label="标签价" min-width="60" />
            <el-table-column prop="jadeMarketPrice" label="市场价" min-width="60" />
            <el-table-column prop="delFlag" label="删除标志" min-width="60" />
            <!-- <el-table-column prop="createTime" label="入库时间" min-width="60" /> -->
            <!-- <el-table-column prop="createBy" label="入库人员" min-width="60" /> -->
            <!-- <el-table-column prop="supplierId" label="供应商" min-width="60" /> -->
            <el-table-column prop="remark" label="备注" min-width="150" />
            <el-table-column prop="createTime" label="创建时间" min-width="100" />
          </el-table>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="drawer = false">取消</el-button>
              <el-button type="primary" @click="drawer = false">
                确定
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
  <div v-else>
    <a-button @click="printShow = false" type="primary" danger>退出打印页面</a-button>
    <print :provider="providerData" :printData="printDataProp"></print>
  </div>
  
</template>    
  
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { getInboundOrderList, merge, } from '@/api/inbound/inbound'
import { getWarehouseListV2, } from '@/api/setting/setting';
import { getSupplierList } from "@/api/user/user"
import { ElMessage } from "element-plus";
import { List } from '@element-plus/icons-vue';
import axios from 'axios';
import { deleteInboundOrders } from '@/api/auth/auth';
//打印界面
import print from '@/print/index.vue'
//打印标签组成
import provider from '@/api/inbound/order/orderProvider.js'
import { createElementTypes, printData } from '@/api/inbound/order/orderProvider.js'
import { ElMessageBox } from 'element-plus';
export default defineComponent({
  name: "HomeView",
  components: {
    List,
    print
  },
  setup() {
    //将打印标签界面传给print子组件
    const providerData = ref(provider)
    const printDataProp = ref(printData)
    const printShow = ref(false)

    const rowDetails = ref([])
    const dialogVisiblePrint = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)//显示设置是否全选
    const drawer = ref(false)

    //注意，selectedRows底下的每个被选中对象有个wmsInboundOrderDetailVOList会输出jadeQuantity数量的货物
    const selectedRows = ref([])
    const searchForm = reactive({  //入库查询表单数据
      jadeCode: '',
      orderCode: '',
      desWarehouseId: '',
      supplierId: '',
      data: [],
      count: 0,
    })
    const inboundOrderData = reactive({//表格数据
      data: [
      ]
    });

    const selectedFilters = ref([])
    const inboundDataColumn = ref([])
    const supplierList = ref([])
    const warehouseList = ref([])
    const tableFilter = ref([//表头自定义数组
      { label: '入库单单号', prop: 'orderCode', width: '205', isSelected: true },
      { label: '入库类型', prop: 'orderType', width: '105', isSelected: true },
      { label: '创建时间', prop: 'createTime', width: '155', isSelected: true },
      { label: '入库仓库', prop: 'warehouseName', width: '120', isSelected: true },
      { label: '入库仓位', prop: 'storageName', width: '100', isSelected: true },
      { label: '入库人员', prop: 'createBy', width: '100', isSelected: true },
      { label: '客户名字', prop: 'clientName', width: '90', isSelected: true },
      { label: '总成本价', prop: 'jadeTotalCostPrice', width: '90', isSelected: true },
      // { label: '成本价', prop: 'jadeCost', width: '90', isSelected: true },
      // { label: '供货价', prop: 'jadeSupplyPrice', width: '90', isSelected: true },
      // { label: '标签价', prop: 'jadeTagPrice', width: '90', isSelected: true },
      // { label: '市场价', prop: 'jadeMarketPrice', width: '90', isSelected: true },
      // { label: '状态', prop: 'status', width: '65', isSelected: true },
      // { label: '删除标志', prop: 'delFlag', width: '85', isSelected: true },
      // { label: '合并', prop: 'merged', width: '105', isSelected: true },
      { label: '订单批次', prop: 'orderBatch', width: '205', isSelected: true },
      { label: '订单日期', prop: 'orderDate', width: '205', isSelected: true },
      // { label: '更新人', prop: 'updateBy', width: '105', isSelected: true },
      // { label: '更新时间', prop: 'updateTime', width: '205', isSelected: true },
      { label: '有效期', prop: 'validDate', width: '145', isSelected: true },
      { label: '备注', prop: 'remark', width: '205', isSelected: true },
      // { label: '入库仓库主键ID', prop: 'warehouseId', width: '105', isSelected: true },
      // { label: '客户ID', prop: 'clientId', width: '105', isSelected: true },
      // { label: '客户编号', prop: 'clientCode', width: '90', isSelected: true },
      // { label: '还货入库关联出库单号', prop: 'outboundOrderCode', width: '205', isSelected: true },
      // { label: '租户ID', prop: 'tenantId', width: '105', isSelected: true },
      // { label: '部门ID', prop: 'deptId', width: '105', isSelected: true },
      // { label: '加工厂主键ID', prop: 'processorId', width: '105', isSelected: true },
      // { label: '还货入库关联出库单主键', prop: 'outboundOrderId', width: '105', isSelected: true },
      // { label: '供应商主键ID', prop: 'supplierId', width: '70', isSelected: true },
      // { label: '数量', prop: 'jadeQuantity', width: '60', isSelected: true },
    ])
    const collapseName = ref('展开');
    const activeNames = ref(false)

    //分页处理
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: inboundOrderData.data.length,
      }
    });

    // loading
    const tableLoading = ref(true)
    const tableData = () => {
      return inboundOrderData.data
    };
    const handleCurrentChange = (e) => {//改变页码
      state.data.page = e;
      handleGetInboundOrderList(e, state.data.limit)
    };
    const handleSizeChange = (e) => {//改变页数限制
      state.data.limit = e;
      handleGetInboundOrderList(state.data.page, e)
    };

    const handleGetInboundOrderList = (page, limit) => {//获取入库单列表
      tableLoading.value = true
      getInboundOrderList({ pageNum: page, pageSize: limit}).then((res) => {
        inboundOrderData.data = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }
    const handleCheckAllChange = (val) => {//全选按钮
      inboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }

    //是否显示数据标签及数据事件
    const handleCheckChange = (val) => {
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inboundDataColumn.value = temp
      selectedFilters.value = inboundDataColumn.value.map(item => item.label)
    }

    onBeforeMount(() => {
      getSupplierList().then((res) => {
        supplierList.value = res.rows
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res
      })
      handleGetInboundOrderList(state.data.page, state.data.limit)
    })

    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inboundDataColumn.value.push(item)
        }
      })
    })
    const mergeOrder = () => {
      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要合并的记录')
      } else {
        merge({ mergeOrderIds: selectedRows.value.map(item => item.id) }).then((res) => {
          if (res.code == 200) {
            ElMessage.success('合并成功')
            handleGetInboundOrderList(state.data.page, state.data.limit)
          } else {
            ElMessage.error('合并失败')
          }
        })
      }

    }
   
    //直接打印入库单
    const printSelectedRows = () => {
      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要打印的记录')
      } else {
        const printWindow = window.open('', '_blank');
        let content = `<html><head><title>打印</title>`

        content += `</head><body>`;
        content += `<h1>入库单记录</h1>`
        content += `<table style="border-collapse: collapse; width: 100%;height: (0.42*width)">`;
        content += `<tr>
                  <th style="border: 1px solid black; padding: 8px;">入库单单号</th>
                  <th style="border: 1px solid black; padding: 8px;">数量</th>
                  <th style="border: 1px solid black; padding: 8px;">供应商</th>
                  <th style="border: 1px solid black; padding: 8px;">客户名字</th>
                  <th style="border: 1px solid black; padding: 8px;">入库时间</th>
                  <th style="border: 1px solid black; padding: 8px;">入库仓库</th>
                  <th style="border: 1px solid black; padding: 8px;">入库人员</th>
                </tr>`;
        console.log(selectedRows.value)
        selectedRows.value.forEach(row => {
          content += `<tr>
                    <td style="border: 1px solid black; padding: 8px;">${row.orderCode}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.jadeQuantity}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.supplierName}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.clientName}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.createTime}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.warehouseName}</td>

                    <td style="border: 1px solid black; padding: 8px;">${row.createBy}</td>
                  </tr>`;
        });
        content += `</table></body></html>`;
        printWindow.document.open();
        printWindow.document.write(content);
        printWindow.document.close()
        printWindow.print()
        printWindow.onload = () => {

          printWindow.print();
          printWindow.close();
        };
        selectedRows.value = []
      }
    }

    //自定义打印入库单
    const designPrint = () => {
      // 需要一次数据更新
      printDataProp.value = printData
      printShow.value = true;
    }

    //已勾选的记录
    const handleChangeSelection = (selection) => {
      // console.log(selection[0].id)
      selectedRows.value = selection
      createElementTypes(selectedRows._rawValue)
      console.log(printData)
    }
    const onSearch = () => {
      tableLoading.value = true
      const params = {
        pageSize: state.data.limit,
        pageNum: state.data.page,
        orderCode: searchForm.orderCode,
        supplierId: searchForm.supplierId,
        warehouseId: searchForm.desWarehouseId
      }
      getInboundOrderList(params).then((res) => {
        inboundOrderData.data = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }

    const openDetails = (row) => { //查看明细
      drawer.value = true
      rowDetails.value = row.wmsInboundOrderDetailVOList
    }
    const printTag = (row) => { //打印标签
      drawer.value = true
      rowDetails.value = row
    }

    //yyl删除
    const handleDeleteInboundOrder = (inboundOrderId) => {
  ElMessageBox.confirm(
    '是否要删除这个入库单？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    deleteInboundOrders(inboundOrderId).then(response => {
      if (response && response.code === 200) {
        // 删除成功，更新前端数据
        const index = inboundOrderData.data.findIndex(item => item.id === inboundOrderId);
        if (index !== -1) {
          inboundOrderData.data.splice(index, 1);
        }
        ElMessage.success('删除成功');
      } else if (response && response.code === 500) {
        // 服务器内部错误
        ElMessage.error('删除失败：服务器内部错误');
      } else {
        // 其他错误
        ElMessage.error('删除失败：' + (response.message || '未知错误'));
      }
    })
    .catch(error => {
      // 网络或其他客户端错误
      console.error('删除入库单失败：', error);
      ElMessage.error('删除失败：请求服务器时发生错误');
    });
  })
  .catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除');
  });
};


    return {
      
      printShow,providerData,printDataProp,designPrint,// 打印的相关变量及方法
      inboundOrderData, isIndeterminate,
      searchForm, rowDetails, drawer, selectedRows,
      collapseName, warehouseList, supplierList,
      activeNames, dialogVisiblePrint, tableLoading,
      inboundDataColumn, selectedFilters, tableFilter, checkAll,
      tableData, mergeOrder, handleChangeSelection, openDetails, printTag, printSelectedRows,
      handleCurrentChange, handleSizeChange, handleCheckAllChange, handleCheckChange,handleDeleteInboundOrder,
      ...toRefs(state),
    };
  },
});


</script>
<style rel="stylesheet/scss" lang="scss" scoped>



.front {
  background-color: #FFF;

  .front-input {
    width: 320px;
  }
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
}

.tail-action {
  display: flex;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}
</style>
  